<?php
class User extends Action implements IAction {
	/**
	 * <h2>日志对象</h2>
	 *
	 * @var Logger
	 */
	private $_logger;

	/**
	 * 构造函数，调用父类构造函数，初始化私有属性
	 */
	public function __construct() {
		parent::__construct ();
		Logger::configure ( ROOT_PATH . 'config/log_config.xml' );
		$this->_logger = Logger::getLogger ( __CLASS__ );
	}

	/**
	 * <h2>用户的首页控制器</h2>
	 *
	 * @see IAction::indexAction()
	 */
	public function indexAction() {
		$user = new UserModel ();
		// $user->create ();
	}

	/**
	 * <h2>用户登录的动作</h2>
	 * <p>首先判断是否已经登录，
	 * 如果已经登录，则直接跳回用户之前来的页面，如果无法获取之前来的页面，则跳转到首页。
	 * 如果之前没有登录，则提取用户提交的参数，并进行授权验证，
	 * 如果登录成功则跳转到登录前的页面，如果获取不到登录前的页面，则跳转到首页。
	 * 如果参数错误，则继续留在登录页面，等待用户再次提交登录凭证。需要保留失败登录的时间，
	 * 在首先得时间内，如果多次登录失败，则禁止用户继续登录。
	 * </p>
	 */
	public function loginAction() {
		$request = new Request ();
		$auth = new Auth ();
		$vr = new SmartyViewHelper ();
		$vr->setTemplateDir ( ROOT_PATH . 'templates/bootstrap' );
		$error = new CMAP ();
		$sessMgr = SessionManager::getSingleton ();
		/*
		 * 检测用户已经登录的状况，如果用户应登录则跳转到登录前的页面，登录状态保存在会话中
		*/
		if ($auth->isAuthed ()) {
			/*
			 * 下边的判断是防止恶意的构造请求，造成跳转的死循环
			* 比如用户已经登录的情况下，构造referer为本动作的请求，如果不做处理则会反复跳转，无法退出
			*/
			$referer = $request->getReferer ();
			$this->_logger->debug ( "###" . $referer );
			if (empty ( $referer )) {
				$this->_redirect ( '/' );
			} else {
				preg_match ( "@^http(s)?://([a-zA-Z0-9.-]+)([a-zA-Z/]+)*@i", $referer, $matches );
				$redirectToReferer = true;
				if (isset ( $matches [3] )) {
					$arr = explode ( '/', trim ( $matches [3], '/' ) );
					$action = isset ( $arr [0] ) ? $arr [0] : "index";
					$method = isset ( $arr [1] ) ? $arr [1] : "index";
					if (strtolower ( $action ) == 'user' && strtolower ( $method ) == 'login') {
						$redirectToReferer = false;
					}
				}
				$this->_logger->debug ( $referer );
				$this->_redirect ( $redirectToReferer ? $referer : '/' );
			}
		}

		if ($request->isPost ()) {
			// 处理用户登录逻辑
			$email = new CEMAIL ( trim ( $request->getPost ( 'email' ) ) );
			$password = new CSTRING ( $request->getPost ( 'password' ) );
			// TODO
			// $verifycode = new CSTRING ( $request->getPost ( 'verifycode' ) );
				
			if (! $email->isValid ()) {
				$error->email = 'email地址无效';
			}
			if (strlen ( $password->getValue () ) < 6) {
				$error->password = '密码长度不能低于6位';
			}
			$uid = null;
			if ($error->isEmpty ()) {
				$identify = new CMAP ();
				$identify->put ( 'email', $email->getValue () );
				$identify->put ( 'password', $password->getValue () );
				$ret = $auth->authLogin ( $identify, $uid );
				if (STATUS_SUCCESS == $ret) {
					$this->_logger->debug ( "User Login success" );
					$sessMgr->setAttribute ( 'UID', $uid );
					$auth->sendAuthCode ( $uid );
					$auth->sendToken ();
					$this->_redirect ( '/' );
				} else {
					$this->_logger->debug ( "User login failed" );
				}
			}
		}
		$vr->assign ('pageTitle', '登录');
		$vr->assign('siteTitle','群格子');
		$vr->assign ( 'error', $error );
		$vr->render ( 'file:user/login.htm' );
	}

	/**
	 * <h2>注销登录</h2>
	 */
	public function logoutAction() {
		$auth = new Auth ();
		$auth->delAuth ();
		$this->_redirect ( '/' );
	}

	/**
	 * <h2>重置密码</h2>
	 */
	public function resetPwdAction() {
		$auth = new Auth ();
		if ($auth->isAuthed ()) {
			$this->_redirect ( '/' );
		}
		$vr = new SmartyViewHelper ();
		$vr->setTemplateDir ( ROOT_PATH . 'templates/bootstrap' );
		$vr->render ( 'file:user/resetpwd.htm' );
	}

	/**
	 * <h2>用戶註冊</h2>
	 */
	public function registerAction() {
		$auth = new Auth ();
		if ($auth->isAuthed ()) {
			$this->_redirect ( '/' );
		}
		$sm = SessionManager::getSingleton ();
		$acl = new ACL ();
		// 判断权限
		if (! $acl->isAllowed ( 'User_register', $sm->getAttribute ( 'groupId' ), $sm->getAttribute ( 'levelId' ) )) {
			$this->_redirect ( '/' );
		}

		$um = new UserModel ();
		$gm = new GroupModel ();
		$request = new Request ();
		$vr = new SmartyViewHelper ();
		$vr->setTemplateDir ( ROOT_PATH . 'templates/bootstrap' );
		$vr->assign ( 'title', '用户注册' );
		$vr->assign ( 'nick', '' );
		$vr->assign ( 'email', '' );
		$this->setError ( 'nick', '' );
		$this->setError ( 'email', '' );
		$this->setError ( 'password', '' );
		// 开始处理POST输入
		if ($request->isPost ()) {
			// 获取参数
			$email = $request->getPost ( 'email' );
			$nick = $request->getPost ( 'nick' );
			$password = $request->getPost ( 'password' );
				
			// 过滤输入
			$email = trim ( filter_var ( $email, FILTER_SANITIZE_EMAIL ) );
			$nick = trim ( filter_var ( $nick, FILTER_SANITIZE_STRING ) );
			$vr->assign ( 'email', $email );
			$vr->assign ( 'nick', $nick );
			/* 验证输入 */
			// 验证Email
			if (strlen ( $email ) == 0) {
				$this->setError ( 'email', '电子邮件地址不能为空' );
			} elseif (strlen ( $email ) > 100) {
				$this->setError ( 'email', '电子邮件地址太长' );
			} elseif (! filter_var ( $email, FILTER_VALIDATE_EMAIL )) {
				$this->setError ( 'email', '电子邮件地址格式不正确' );
			} elseif ($um->isEmailExists ( $email )) {
				$this->setError ( 'email', '电子邮件已经存在' );
			} else {
				$this->setError ( 'email', '' );
			}
			// 验证用户昵称
			$nicklen = strlen ( $nick );
			if ($nicklen == 0) {
				$this->setError ( 'nick', '昵称不能为空' );
			} elseif ($nicklen < 3) {
				$this->setError ( 'nick', '昵称长度不能小于3个字符' );
			} elseif ($nicklen > 20) {
				$this->setError ( 'nick', '昵称长度不能超过20个字符' );
			} elseif (! filter_var ( $nick, FILTER_VALIDATE_REGEXP, array (
					'options' => array (
							// 'regexp' =>
							// '/^[0-9a-zA-Z_\x{4e00}-\x{9fa5}\x{3130}-\x{318f}\x{AC00}-\x{D7A3}\x{0800}-\x{4e00}]+$/u'
							'regexp' => '/^([0-9a-zA-Z ]|[^\x00-\xff])+$/u'
					)
			) )) {
				$this->setError ( 'nick', '昵称中含有不允许的字符' );
			} elseif ($um->isNickExists ( $nick )) {
				$this->setError ( 'nick', '用户昵称已经存在' );
			} else {
				$this->setError ( 'nick', '' );
			}
			// 验证密码长度
			if (strlen ( $password ) < 6 || strlen ( $password ) > 20) {
				$this->setError ( 'password', '密码长度必须在6到20个字符之间' );
			} else {
				$this->setError ( 'password', '' );
			}
				
			// 如果没有错误则保存，否则给出提示信息
			if (! $this->hasError ()) {
				// save
				// 获取用户组的ID
				if (defined ( 'REGISTER_VERIFY' ) && REGISTER_VERIFY) {
					$groupid = $gm->getIdByName ( 'unverify' );
				} else {
					$groupid = $gm->getIdByName ( 'member' );
				}
				$uid = $um->register ( array (
						'email' => $email,
						'nick' => $nick,
						'password' => $password,
						'groupid' => $groupid
				) );
				if ($uid) {
					// 设置用户登录
					$um->login ( $email, $password );
					$this->_showStatus ( '注册成功', '/user' );
				} else {
					$this->_showStatus ( '注册失败', '/user/register' ); // 再次跳转到注册页面
				}
			}
		}
		$vr->assign ( 'error', $this->getError () );
		$vr->render ( 'file:user/register.htm' );
	}
	/*
	 * (non-PHPdoc) @see IAction::addListener()
	*/
	public function addListener(ActionListener $listener) {
		// TODO Auto-generated method stub
	}

	/*
	 * (non-PHPdoc) @see IAction::removeListener()
	*/
	public function removeListener(ActionListener $listener) {
		// TODO Auto-generated method stub
	}

	/*
	 * (non-PHPdoc) @see IAction::removeAllListener()
	*/
	public function removeAllListener() {
		// TODO Auto-generated method stub
	}
}
